package com.sailfish.template.infra.common.utils;

/**
 * @author XIAXINYU3
 * @date 2021/11/2
 */

import com.zaxxer.hikari.HikariPoolMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ConditionalOnExpression("${spring.datasource.hikari.registerMbeans} == true")
public class DBMonitor {
    @Autowired
    HikariPoolMXBean poolProxy;

    @Scheduled(fixedRate = 10000)
    public void printPool() {
        if (poolProxy == null) {
            log.info("Hikari not initialized, please wait...");
        } else {
            log.info("HikariPoolState = "
                    + "Active=[" + String.valueOf(poolProxy.getActiveConnections() + "] "
                    + "Idle=[" + String.valueOf(poolProxy.getIdleConnections() + "] "
                    + "Wait=[" + poolProxy.getThreadsAwaitingConnection() + "] "
                    + "Total=[" + poolProxy.getTotalConnections() + "]")));
        }
    }
}
